// 在 utils/formTips.ts 中

// 缓存对象
let tipsCache: Record<string, any> | null = null
let loadingPromise: Promise<any> | null = null

export const getFormTip = async (formType: string, field: string): Promise<string> => {
  try {
    // 如果缓存中存在数据，直接返回
    if (tipsCache) {
      return tipsCache[formType]?.[field] || ''
    }

    // 如果正在加载中，等待加载完成
    if (loadingPromise) {
      await loadingPromise
      return tipsCache?.[formType]?.[field] || ''
    }

    // 开始加载数据
    loadingPromise = loadTipsData()
    await loadingPromise

    return tipsCache?.[formType]?.[field] || ''
  } catch (error) {
    console.warn('获取提示信息失败:', error)
    return ''
  }
}

// 加载提示数据
const loadTipsData = async (): Promise<void> => {
  try {
    const BASE_URL = import.meta.env.VITE_APP_BASE_URL || '/'
    const response = await fetch(`${BASE_URL}formTips.json`)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    tipsCache = await response.json()
  } catch (error) {
    console.warn('加载提示信息失败:', error)
    tipsCache = {}
  } finally {
    loadingPromise = null
  }
}

// 清空缓存（如果需要重新加载）
export const clearTipsCache = (): void => {
  tipsCache = null
  loadingPromise = null
}

// 预加载提示数据（可选）
export const preloadFormTips = (): Promise<void> => {
  if (tipsCache || loadingPromise) {
    return loadingPromise || Promise.resolve()
  }
  return loadTipsData()
}

export const FORM_TYPES = {
  DOMESTIC_COMPONENTS: 'c_domestic_components',
  DOMESTIC_MATERIALS: 'c_domestic_materials',
  DOMESTIC_ELECTROMECHANICALS: 'c_domestic_electromechanicals',
  DOMESTIC_SOFTWARES: 'c_domestic_softwares',
  IMPORTED_COMPONENTS: 'c_imported_components',
  IMPORTED_MATERIALS: 'c_imported_materials',
  IMPORTED_ELECTROMECHANICALS: 'c_imported_electromechanicals',
  IMPORTED_SOFTWARES: 'c_imported_softwares',
} as const
